<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#8B4513',
                        secondary: '#D2B48C',
                        board: '#E6B87A',
                        black: '#000000',
                        white: '#FFFFFF',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .board-grid {
                background-size: 100% 100%;
                background-image: linear-gradient(to right, #000 1px, transparent 1px),
                                  linear-gradient(to bottom, #000 1px, transparent 1px);
            }
            .piece-black {
                background: radial-gradient(circle at 35% 35%, #555, #000);
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
            }
            .piece-white {
                background: radial-gradient(circle at 35% 35%, #fff, #ddd);
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
                border: 1px solid rgba(0, 0, 0, 0.1);
            }
            .piece-preview {
                opacity: 0.5;
                transform: scale(0.95) translate(-50%, -50%);
            }
            .animate-pulse {
                animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            @keyframes pulse {
                0%, 100% {
                    opacity: 1;
                }
                50% {
                    opacity: 0.7;
                }
            }
        }
    </style>
</head>
<body class="bg-secondary min-h-screen flex flex-col items-center justify-center p-4">
    <div class="max-w-4xl w-full bg-white rounded-xl shadow-lg overflow-hidden">
        <header class="bg-primary text-white p-4 text-center">
            <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold">五子棋</h1>
        </header>
        
        <main class="p-4 md:p-8 flex flex-col md:flex-row gap-6">
            <!-- 游戏区域 -->
            <div class="w-full md:w-3/4 flex flex-col items-center">
                <div id="game-board" class="relative w-full max-w-2xl aspect-square bg-board rounded-lg shadow-md overflow-hidden board-grid" style="background-size: calc(100% / 14) calc(100% / 14);">
                    <!-- 预览棋子将通过JS动态添加 -->
                </div>
                
                <div class="mt-4 w-full flex justify-between items-center">
                    <button id="restart-btn" class="bg-primary hover:bg-primary/90 text-white py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                        <i class="fa fa-refresh mr-2"></i> 重新开始
                    </button>
                    
                    <button id="undo-btn" class="bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                        <i class="fa fa-undo mr-2"></i> 悔棋
                    </button>
                    
                    <button id="hint-btn" class="bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                        <i class="fa fa-lightbulb-o mr-2"></i> 提示
                    </button>
                </div>
            </div>
            
            <!-- 游戏信息区域 -->
            <div class="w-full md:w-1/4 bg-gray-50 rounded-lg p-4">
                <div class="mb-6">
                    <h2 class="text-lg font-bold mb-2 text-primary">游戏状态</h2>
                    <div id="game-status" class="text-xl font-semibold py-2 px-4 bg-white rounded shadow-sm">
                        <span id="current-player" class="inline-block w-6 h-6 rounded-full piece-black align-middle mr-2"></span>
                        <span>黑方回合</span>
                    </div>
                </div>
                
                <div class="mb-6">
                    <h2 class="text-lg font-bold mb-2 text-primary">游戏设置</h2>
                    <div class="space-y-3">
                        <div>
                            <label class="block mb-1">棋盘大小</label>
                            <select id="board-size" class="w-full p-2 border border-gray-300 rounded">
                                <option value="9">9×9</option>
                                <option value="13" selected>13×13</option>
                                <option value="15">15×15</option>
                                <option value="19">19×19</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="auto-win" class="mr-2" checked>
                                <span>自动检测胜利</span>
                            </label>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="show-coordinates" class="mr-2">
                                <span>显示坐标</span>
                            </label>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="show-preview" class="mr-2" checked>
                                <span>显示预览</span>
                            </label>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="snap-to-grid" class="mr-2" checked>
                                <span>自动对齐网格</span>
                            </label>
                        </div>
                    </div>
                </div>
                
                <div>
                    <h2 class="text-lg font-bold mb-2 text-primary">游戏规则</h2>
                    <ul class="text-sm space-y-1 list-disc pl-5">
                        <li>黑方先行，双方轮流落子</li>
                        <li>先形成五子连珠者获胜</li>
                        <li>点击棋盘放置棋子，点击"重新开始"重置游戏</li>
                        <li>支持悔棋和提示功能</li>
                    </ul>
                </div>
            </div>
        </main>
        
        <footer class="bg-gray-100 text-center p-3 text-gray-600 text-sm">
            <p>© 2025 五子棋游戏 | 一个简单的HTML5五子棋实现</p>
        </footer>
    </div>

    <!-- 胜利弹窗 -->
    <div id="win-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-8 max-w-md w-full transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
            <div class="text-center">
                <div id="winner-icon" class="w-20 h-20 rounded-full mx-auto mb-4 piece-black"></div>
                <h2 class="text-2xl font-bold mb-2" id="winner-text">黑方胜利！</h2>
                <p class="text-gray-600 mb-6">恭喜您获得胜利！</p>
                <button id="new-game-btn" class="bg-primary hover:bg-primary/90 text-white py-3 px-6 rounded-lg transition-all duration-300 text-lg">
                    开始新游戏
                </button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 游戏常量和变量
            const BOARD_SIZE_DEFAULT = 13;
            let boardSize = BOARD_SIZE_DEFAULT;
            let gameBoard = [];
            let currentPlayer = 'black';
            let gameOver = false;
            let moveHistory = [];
            let hintPosition = null;
            let previewPiece = null;
            let gridOffset = 0; // 偏移量用于居中网格
            
            // DOM元素
            const gameBoardEl = document.getElementById('game-board');
            const gameStatusEl = document.getElementById('game-status');
            const currentPlayerEl = document.getElementById('current-player');
            const restartBtn = document.getElementById('restart-btn');
            const undoBtn = document.getElementById('undo-btn');
            const hintBtn = document.getElementById('hint-btn');
            const boardSizeSelect = document.getElementById('board-size');
            const autoWinCheckbox = document.getElementById('auto-win');
            const showCoordinatesCheckbox = document.getElementById('show-coordinates');
            const showPreviewCheckbox = document.getElementById('show-preview');
            const snapToGridCheckbox = document.getElementById('snap-to-grid');
            const winModal = document.getElementById('win-modal');
            const modalContent = document.getElementById('modal-content');
            const winnerIcon = document.getElementById('winner-icon');
            const winnerText = document.getElementById('winner-text');
            const newGameBtn = document.getElementById('new-game-btn');
            
            // 初始化游戏
            function initGame() {
                // 清空棋盘
                gameBoardEl.innerHTML = '';
                gameBoard = Array(boardSize).fill().map(() => Array(boardSize).fill(null));
                moveHistory = [];
                gameOver = false;
                currentPlayer = 'black';
                hintPosition = null;
                previewPiece = null;
                
                // 计算网格偏移量
                gridOffset = 1 / (boardSize - 1) / 2 * 100; // 网格单元格大小的一半（百分比）
                
                // 更新游戏状态
                updateGameStatus();
                
                // 创建棋盘网格
                createBoardGrid();
                
                // 添加星位点
                addStarPoints();
            }
            
            // 创建棋盘网格
            function createBoardGrid() {
                // 设置背景大小和偏移以居中网格
                gameBoardEl.style.backgroundSize = `calc(100% / ${boardSize - 1}) calc(100% / ${boardSize - 1})`;
                gameBoardEl.style.backgroundPosition = `${gridOffset}% ${gridOffset}%`;
                
                // 添加鼠标移动事件以显示预览
                gameBoardEl.addEventListener('mousemove', handleMouseMove);
                
                // 添加点击事件
                gameBoardEl.addEventListener('click', handleBoardClick);
                
                // 显示/隐藏坐标
                updateCoordinates();
            }
            
            // 处理鼠标移动以显示预览
            function handleMouseMove(e) {
                if (gameOver || !showPreviewCheckbox.checked) {
                    removePreviewPiece();
                    return;
                }
                
                // 获取鼠标位置
                const rect = gameBoardEl.getBoundingClientRect();
                const xRatio = (e.clientX - rect.left) / rect.width;
                const yRatio = (e.clientY - rect.top) / rect.height;
                
                // 计算网格坐标
                let x, y;
                if (snapToGridCheckbox.checked) {
                    // 对齐到最近的网格交叉点
                    x = Math.round(xRatio * (boardSize - 1));
                    y = Math.round(yRatio * (boardSize - 1));
                } else {
                    // 精确放置在鼠标位置
                    x = Math.floor(xRatio * (boardSize - 1));
                    y = Math.floor(yRatio * (boardSize - 1));
                    
                    // 确保不超出边界
                    x = Math.max(0, Math.min(boardSize - 1, x));
                    y = Math.max(0, Math.min(boardSize - 1, y));
                }
                
                // 检查坐标是否有效且为空
                if (x >= 0 && x < boardSize && y >= 0 && y < boardSize && !gameBoard[x][y]) {
                    updatePreviewPiece(x, y);
                } else {
                    removePreviewPiece();
                }
            }
            
            // 更新预览棋子
            function updatePreviewPiece(x, y) {
                // 移除现有预览
                removePreviewPiece();
                
                // 创建预览棋子
                previewPiece = document.createElement('div');
                previewPiece.className = `piece absolute rounded-full shadow-md piece-preview ${currentPlayer === 'black' ? 'piece-black' : 'piece-white'}`;
                previewPiece.style.width = `calc(100% / ${boardSize} - 8px)`;
                previewPiece.style.height = `calc(100% / ${boardSize} - 8px)`;
                
                // 调整位置以适应网格偏移
                previewPiece.style.left = `calc(${x * 100 / (boardSize - 1)}% + ${gridOffset}%)`;
                previewPiece.style.top = `calc(${y * 100 / (boardSize - 1)}% + ${gridOffset}%)`;
                previewPiece.style.transform = 'translate(-50%, -50%)'; // 居中定位
                
                previewPiece.style.zIndex = 5;
                previewPiece.dataset.x = x;
                previewPiece.dataset.y = y;
                
                // 添加到棋盘
                gameBoardEl.appendChild(previewPiece);
            }
            
            // 移除预览棋子
            function removePreviewPiece() {
                if (previewPiece && previewPiece.parentNode) {
                    previewPiece.parentNode.removeChild(previewPiece);
                }
                previewPiece = null;
            }
            
            // 更新坐标显示
            function updateCoordinates() {
                // 移除现有坐标元素
                document.querySelectorAll('.board-coordinate').forEach(el => el.remove());
                
                if (showCoordinatesCheckbox.checked) {
                    // 添加X轴坐标
                    for (let x = 0; x < boardSize; x++) {
                        const coordEl = document.createElement('div');
                        coordEl.className = 'board-coordinate absolute text-gray-600 font-medium text-xs';
                        coordEl.style.left = `calc(${x * 100 / (boardSize - 1)}% + ${gridOffset}% - 0.5em)`;
                        coordEl.style.bottom = '-1.5em';
                        coordEl.textContent = String.fromCharCode(65 + x); // A, B, C...
                        gameBoardEl.appendChild(coordEl);
                    }
                    
                    // 添加Y轴坐标
                    for (let y = 0; y < boardSize; y++) {
                        const coordEl = document.createElement('div');
                        coordEl.className = 'board-coordinate absolute text-gray-600 font-medium text-xs';
                        coordEl.style.left = '-1.5em';
                        coordEl.style.top = `calc(${y * 100 / (boardSize - 1)}% + ${gridOffset}% - 0.5em)`;
                        coordEl.textContent = boardSize - y;
                        gameBoardEl.appendChild(coordEl);
                    }
                }
            }
            
            // 添加星位点（天元和星位）
            function addStarPoints() {
                // 移除现有星位点
                document.querySelectorAll('.star-point').forEach(el => el.remove());
                
                // 根据棋盘大小确定星位点
                let starPoints = [];
                
                if (boardSize >= 13) {
                    const center = Math.floor(boardSize / 2);
                    starPoints.push({x: center, y: center}); // 天元
                    
                    if (boardSize >= 15) {
                        const offset = boardSize === 15 ? 3 : 4;
                        starPoints.push(
                            {x: offset, y: offset}, // 左上
                            {x: offset, y: center}, // 左中
                            {x: offset, y: boardSize - offset - 1}, // 左下
                            {x: center, y: offset}, // 中上
                            {x: center, y: boardSize - offset - 1}, // 中下
                            {x: boardSize - offset - 1, y: offset}, // 右上
                            {x: boardSize - offset - 1, y: center}, // 右中
                            {x: boardSize - offset - 1, y: boardSize - offset - 1} // 右下
                        );
                    }
                }
                
                // 添加星位点并考虑网格偏移
                starPoints.forEach(point => {
                    const starPoint = document.createElement('div');
                    starPoint.className = 'star-point absolute bg-black rounded-full';
                    starPoint.style.width = '6px';
                    starPoint.style.height = '6px';
                    starPoint.style.left = `calc(${point.x * 100 / (boardSize - 1)}% + ${gridOffset}% - 3px)`;
                    starPoint.style.top = `calc(${point.y * 100 / (boardSize - 1)}% + ${gridOffset}% - 3px)`;
                    gameBoardEl.appendChild(starPoint);
                });
            }
            
            // 处理棋盘点击
            function handleBoardClick(e) {
                if (gameOver) return;
                
                // 移除预览棋子
                removePreviewPiece();
                
                // 获取点击位置
                const rect = gameBoardEl.getBoundingClientRect();
                const xRatio = (e.clientX - rect.left) / rect.width;
                const yRatio = (e.clientY - rect.top) / rect.height;
                
                // 计算网格坐标
                let x, y;
                if (snapToGridCheckbox.checked) {
                    // 对齐到最近的网格交叉点
                    x = Math.round(xRatio * (boardSize - 1));
                    y = Math.round(yRatio * (boardSize - 1));
                } else {
                    // 精确放置在鼠标位置
                    x = Math.floor(xRatio * (boardSize - 1));
                    y = Math.floor(yRatio * (boardSize - 1));
                    
                    // 确保不超出边界
                    x = Math.max(0, Math.min(boardSize - 1, x));
                    y = Math.max(0, Math.min(boardSize - 1, y));
                }
                
                // 检查坐标是否有效且为空
                if (x >= 0 && x < boardSize && y >= 0 && y < boardSize && !gameBoard[x][y]) {
                    // 放置棋子
                    placePiece(x, y);
                    
                    // 检查胜利
                    if (autoWinCheckbox.checked && checkWin(x, y)) {
                        gameOver = true;
                        showWinModal();
                    } else {
                        // 切换玩家
                        currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
                        updateGameStatus();
                        
                        // 清除提示
                        clearHint();
                    }
                }
            }
            
            // 放置棋子
            function placePiece(x, y) {
                // 更新游戏状态
                gameBoard[x][y] = currentPlayer;
                moveHistory.push({x, y, player: currentPlayer});
                
                // 创建棋子元素
                const piece = document.createElement('div');
                piece.className = `piece absolute rounded-full transition-all duration-300 transform scale-0 opacity-0 shadow-md ${currentPlayer === 'black' ? 'piece-black' : 'piece-white'}`;
                piece.style.width = `calc(100% / ${boardSize} - 8px)`;
                piece.style.height = `calc(100% / ${boardSize} - 8px)`;
                
                // 调整位置以适应网格偏移
                piece.style.left = `calc(${x * 100 / (boardSize - 1)}% + ${gridOffset}%)`;
                piece.style.top = `calc(${y * 100 / (boardSize - 1)}% + ${gridOffset}%)`;
                piece.style.transform = 'translate(-50%, -50%)'; // 新增：将元素相对于中心点定位
                
                piece.style.zIndex = 10;
                piece.dataset.x = x;
                piece.dataset.y = y;
                
                // 添加到棋盘
                gameBoardEl.appendChild(piece);
                
                // 触发动画
                setTimeout(() => {
                    piece.classList.remove('scale-0', 'opacity-0');
                    piece.classList.add('scale-100', 'opacity-100');
                }, 10);
            }
            
            // 显示提示
            function showHint() {
                // 清除现有提示
                clearHint();
                
                // 简单AI提示：找到能形成连线的位置
                let bestScore = 0;
                let bestPosition = null;
                
                // 检查棋盘上的每个位置
                for (let x = 0; x < boardSize; x++) {
                    for (let y = 0; y < boardSize; y++) {
                        if (!gameBoard[x][y]) {
                            // 计算此位置的得分
                            const score = evaluatePosition(x, y, currentPlayer);
                            
                            // 如果得分更高，则更新最佳位置
                            if (score > bestScore) {
                                bestScore = score;
                                bestPosition = {x, y};
                            }
                        }
                    }
                }
                
                // 如果找到最佳位置，则显示提示
                if (bestPosition) {
                    hintPosition = bestPosition;
                    
                    const hint = document.createElement('div');
                    hint.className = 'hint absolute rounded-full border-2 border-yellow-400 bg-yellow-200/50 transition-all duration-300 opacity-0 animate-pulse';
                    hint.style.width = `calc(100% / ${boardSize} - 4px)`;
                    hint.style.height = `calc(100% / ${boardSize} - 4px)`;
                    
                    // 调整位置以适应网格偏移
                    hint.style.left = `calc(${bestPosition.x * 100 / (boardSize - 1)}% + ${gridOffset}%)`;
                    hint.style.top = `calc(${bestPosition.y * 100 / (boardSize - 1)}% + ${gridOffset}%)`;
                    hint.style.transform = 'translate(-50%, -50%)'; // 居中定位
                    
                    hint.style.zIndex = 5;
                    hint.id = 'hint-marker';
                    
                    gameBoardEl.appendChild(hint);
                    
                    // 触发动画
                    setTimeout(() => {
                        hint.classList.remove('opacity-0');
                        hint.classList.add('opacity-100');
                    }, 10);
                }
            }
            
            // 清除提示
            function clearHint() {
                const hintMarker = document.getElementById('hint-marker');
                if (hintMarker) {
                    hintMarker.classList.add('opacity-0');
                    setTimeout(() => {
                        if (hintMarker.parentNode) {
                            hintMarker.parentNode.removeChild(hintMarker);
                        }
                    }, 300);
                }
                hintPosition = null;
            }
            
            // 评估位置得分（简化AI）
            function evaluatePosition(x, y, player) {
                const directions = [
                    [1, 0],   // 水平
                    [0, 1],   // 垂直
                    [1, 1],   // 对角线
                    [1, -1]   // 反对角线
                ];
                
                let maxScore = 0;
                
                // 检查每个方向
                for (const [dx, dy] of directions) {
                    let score = 0;
                    let continuous = 0;
                    let blocked = 0;
                    
                    // 检查正方向
                    for (let i = 1; i <= 4; i++) {
                        const nx = x + dx * i;
                        const ny = y + dy * i;
                        
                        if (nx < 0 || nx >= boardSize || ny < 0 || ny >= boardSize) {
                            blocked++;
                            break;
                        }
                        
                        if (gameBoard[nx][ny] === player) {
                            continuous++;
                        } else if (gameBoard[nx][ny] !== null) {
                            blocked++;
                            break;
                        } else {
                            break;
                        }
                    }
                    
                    // 检查负方向
                    for (let i = 1; i <= 4; i++) {
                        const nx = x - dx * i;
                        const ny = y - dy * i;
                        
                        if (nx < 0 || nx >= boardSize || ny < 0 || ny >= boardSize) {
                            blocked++;
                            break;
                        }
                        
                        if (gameBoard[nx][ny] === player) {
                            continuous++;
                        } else if (gameBoard[nx][ny] !== null) {
                            blocked++;
                            break;
                        } else {
                            break;
                        }
                    }
                    
                    // 计算得分
                    if (continuous === 4) {
                        score = 10000; // 五连
                    } else if (continuous === 3 && blocked === 0) {
                        score = 1000; // 活四
                    } else if (continuous === 3 && blocked === 1) {
                        score = 100; // 冲四
                    } else if (continuous === 2 && blocked === 0) {
                        score = 50; // 活三
                    } else if (continuous === 2 && blocked === 1) {
                        score = 10; // 冲三
                    } else if (continuous === 1 && blocked === 0) {
                        score = 5; // 活二
                    }
                    
                    maxScore = Math.max(maxScore, score);
                }
                
                return maxScore;
            }
            
            // 检查胜利
            function checkWin(x, y) {
                const player = gameBoard[x][y];
                const directions = [
                    [1, 0],   // 水平
                    [0, 1],   // 垂直
                    [1, 1],   // 对角线
                    [1, -1]   // 反对角线
                ];
                
                // 检查每个方向
                for (const [dx, dy] of directions) {
                    let count = 1;  // 当前位置已有棋子
                    
                    // 检查正方向
                    for (let i = 1; i <= 4; i++) {
                        const nx = x + dx * i;
                        const ny = y + dy * i;
                        
                        if (nx < 0 || nx >= boardSize || ny < 0 || ny >= boardSize || gameBoard[nx][ny] !== player) {
                            break;
                        }
                        
                        count++;
                    }
                    
                    // 检查负方向
                    for (let i = 1; i <= 4; i++) {
                        const nx = x - dx * i;
                        const ny = y - dy * i;
                        
                        if (nx < 0 || nx >= boardSize || ny < 0 || ny >= boardSize || gameBoard[nx][ny] !== player) {
                            break;
                        }
                        
                        count++;
                    }
                    
                    // 如果形成五子连线，返回胜利
                    if (count >= 5) {
                        // 高亮显示获胜棋子
                        highlightWinningPieces(x, y, dx, dy, count);
                        return true;
                    }
                }
                
                return false;
            }
            
            // 高亮显示获胜棋子
            function highlightWinningPieces(x, y, dx, dy, count) {
                // 正方向
                for (let i = 0; i < count; i++) {
                    const nx = x + dx * i;
                    const ny = y + dy * i;
                    
                    if (nx < 0 || nx >= boardSize || ny < 0 || ny >= boardSize || gameBoard[nx][ny] !== currentPlayer) {
                        continue;
                    }
                    
                    const piece = document.querySelector(`.piece[data-x="${nx}"][data-y="${ny}"]`);
                    if (piece) {
                        piece.classList.add('ring-2', 'ring-yellow-400', 'ring-offset-2', 'animate-pulse');
                    }
                }
                
                // 负方向
                for (let i = 1; i < count; i++) {
                    const nx = x - dx * i;
                    const ny = y - dy * i;
                    
                    if (nx < 0 || nx >= boardSize || ny < 0 || ny >= boardSize || gameBoard[nx][ny] !== currentPlayer) {
                        continue;
                    }
                    
                    const piece = document.querySelector(`.piece[data-x="${nx}"][data-y="${ny}"]`);
                    if (piece) {
                        piece.classList.add('ring-2', 'ring-yellow-400', 'ring-offset-2', 'animate-pulse');
                    }
                }
            }
            
            // 悔棋
            function undoMove() {
                if (moveHistory.length === 0 || gameOver) return;
                
                // 获取最后一步
                const lastMove = moveHistory.pop();
                gameBoard[lastMove.x][lastMove.y] = null;
                
                // 移除棋子
                const piece = document.querySelector(`.piece[data-x="${lastMove.x}"][data-y="${lastMove.y}"]`);
                if (piece) {
                    piece.classList.add('scale-0', 'opacity-0');
                    setTimeout(() => {
                        if (piece.parentNode) {
                            piece.parentNode.removeChild(piece);
                        }
                    }, 300);
                }
                
                // 切换回上一个玩家
                currentPlayer = lastMove.player;
                updateGameStatus();
                
                // 清除提示
                clearHint();
            }
            
            // 更新游戏状态显示
            function updateGameStatus() {
                currentPlayerEl.className = `inline-block w-6 h-6 rounded-full align-middle mr-2 ${currentPlayer === 'black' ? 'piece-black' : 'piece-white'}`;
                gameStatusEl.innerHTML = `<span id="current-player" class="inline-block w-6 h-6 rounded-full align-middle mr-2 ${currentPlayer === 'black' ? 'piece-black' : 'piece-white'}"></span>
                <span>${currentPlayer === 'black' ? "黑方回合" : "白方回合"}</span>`;
            }
            
            // 显示胜利弹窗
            function showWinModal() {
                winnerIcon.className = `w-20 h-20 rounded-full mx-auto mb-4 ${currentPlayer === 'black' ? 'piece-black' : 'piece-white'}`;
                winnerText.textContent = `${currentPlayer === 'black' ? '黑方' : '白方'}胜利！`;
                
                winModal.classList.remove('hidden');
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100');
                }, 10);
            }
            
            // 隐藏胜利弹窗
            function hideWinModal() {
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                setTimeout(() => {
                    winModal.classList.add('hidden');
                }, 300);
            }
            
            // 事件监听器
            restartBtn.addEventListener('click', () => {
                // 确认对话框
                if (moveHistory.length > 0 && !gameOver) {
                    if (confirm('确定要重新开始游戏吗？当前进度将丢失。')) {
                        initGame();
                    }
                } else {
                    initGame();
                }
            });
            
            undoBtn.addEventListener('click', undoMove);
            
            hintBtn.addEventListener('click', showHint);
            
            boardSizeSelect.addEventListener('change', () => {
                boardSize = parseInt(boardSizeSelect.value);
                initGame();
            });
            
            autoWinCheckbox.addEventListener('change', () => {
                // 可以添加视觉反馈
            });
            
            showCoordinatesCheckbox.addEventListener('change', updateCoordinates);
            
            showPreviewCheckbox.addEventListener('change', () => {
                removePreviewPiece();
            });
            
            snapToGridCheckbox.addEventListener('change', () => {
                removePreviewPiece();
            });
            
            newGameBtn.addEventListener('click', () => {
                hideWinModal();
                initGame();
            });
            
            winModal.addEventListener('click', (e) => {
                if (e.target === winModal) {
                    hideWinModal();
                    initGame();
                }
            });
            
            // 初始化游戏
            initGame();
        });
    </script>
</body>
</html>
    